package logic

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/ryon-wen/own-utils/own"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"2106A-zg6/baidu/srv/internal/svc"
	"2106A-zg6/baidu/srv/models"
	"2106A-zg6/baidu/srv/nacos_init"
	"2106A-zg6/baidu/srv/pb/baidu"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileSearchLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFileSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileSearchLogic {
	return &FileSearchLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FileSearchLogic) FileSearch(in *baidu.FileSearchRequest) (*baidu.FileSearchResponse, error) {

	var na nacos_init.NacosContent

	own.InitElasticsearch(&own.ElasticSearch{
		Host:     na.Es.Host,
		Port:     int(na.Es.Port),
		IndexKey: na.Es.IndexKey,
	})

	//根据创建时间  来排序 倒序
	sort := in.Sort

	fmt.Println(sort)
	var req reqSearch
	req.Query.Match.GoodsName = "东阿阿胶"
	search, err := own.EsSearch(req)
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}

	var f []models.File

	//for _, v := range search {
	json.Unmarshal([]byte(search), f)
	//}

	var data []*baidu.File

	for _, v := range f {
		data = append(data, ModelRespFile(v))
	}

	return &baidu.FileSearchResponse{
		Files: data,
	}, nil
}

type reqSearch struct {
	Query struct {
		Match struct {
			GoodsName string `json:"GoodsName"`
		} `json:"match"`
	} `json:"query"`
}
